home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 8_3.lha / 8_3 / 8_3_date.c next >
C/C++ Source or Header  |  1993-08-08  |  2KB  |  100 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / Exercise 8.3
  6. / Read in a date, with error checking
  7. include <stream.h>
  8. include <errno.h>
  9. include <stdlib.h>
  10. include <date.h>
  11.  
  12. / return the maximum # of days
  13. / in a given year and month
  14. nt maxday(long year, long month)
  15.  
  16.    // check for february and leap years
  17.    if (month == 2)
  18. if ((year % 4 == 0) &&
  19.     ((year % 100 != 0) || (year % 400 == 0)))
  20.     return 29;
  21.  
  22. else
  23.     return 28;
  24.  
  25.    // the rest are constant
  26.    static int numdays[] =
  27. {
  28. 31, 28, 31, 30, 31, 30,
  29. 31, 31, 30, 31, 30, 31
  30. };
  31.  
  32.    return numdays[month-1];
  33.  
  34.  
  35. nt read_date(ostream &out, istream &in, date *val)
  36.  
  37.    // set up flushing of the output stream
  38.    ostream *old = in.tie(&out);
  39.  
  40.    // loop until we get something right
  41.    for ( ; ; out << "Try again\n")
  42. {
  43. // read a year number
  44. out << "Type a year: ";
  45. char buf[256], c;
  46. if (!cin.get(buf, 256))
  47.     {
  48.     in.tie(old);
  49.     return 0;
  50.     }
  51. in.get(c);
  52.  
  53. // check the integer
  54. char *p;
  55. errno = 0;
  56. long year = strtol(buf, &p, 10);
  57. if (*p || (p == buf) || errno)
  58.     continue;
  59.  
  60. // read a month number
  61. out << "Type a month (a number from 1 - 12): ";
  62. if (!cin.get(buf, 256))
  63.     {
  64.     in.tie(old);
  65.     return 0;
  66.     }
  67. in.get(c);
  68.  
  69. // check the integer
  70. errno = 0;
  71. long month = strtol(buf, &p, 10);
  72. if (*p || (p == buf) || errno ||
  73.     (month < 1) || (month > 12))
  74.     continue;
  75.  
  76. // read a day of the month
  77. int maxd = maxday(year, month);
  78. out << "Type a day (a number from 1 - " <<
  79.     maxd << "): ";
  80. if (!cin.get(buf, 256))
  81.     {
  82.     in.tie(old);
  83.     return 0;
  84.     }
  85. in.get(c);
  86.  
  87. // check the integer
  88. errno = 0;
  89. long day = strtol(buf, &p, 10);
  90. if (*p || (p == buf) || errno ||
  91.     (day < 1) || (day > maxd))
  92.     continue;
  93.  
  94. // return the value, restoring the old tie first
  95. in.tie(old);
  96. val->set((int)month, (int)day, (int)year);
  97. return 1;
  98. }
  99.  
  100.